package com.beordie.version_2.mvc;

import com.beordie.annotation.BODRequestParam;
import com.beordie.utils.StringUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description
 * @Date 2022/2/17 10:07
 * @Created 30500
 */
public class BODHandlerAdapter {

    public BODModelAndView handle(HttpServletRequest req,
                                  HttpServletResponse resp,
                                  BODHandlerMapping handler) throws InvocationTargetException, IllegalAccessException {
        Method method = handler.getMethod();

        //  填充参数
        Map<String, Integer> paramIndex = new HashMap<>();
        Annotation[][] annotations = method.getParameterAnnotations();
        for (int i = 0; i < annotations.length; i++) {
            for (Annotation annotation : annotations[i]) {
                if (!(annotation instanceof BODRequestParam)) { continue; }
                String paramName = ((BODRequestParam) annotation).name();
                if (!"".equals(paramName.trim())) {
                    paramIndex.put(paramName, i);
                }
            }
        }
        //  获取参数位置
        Class<?>[] parameterTypes = method.getParameterTypes();
        for (int i = 0; i < parameterTypes.length; i++) {
            Class<?> type = parameterTypes[i];
            if (type == HttpServletRequest.class || type == HttpServletResponse.class) {
                paramIndex.put(type.getName(), i);
            }
        }
        //  设置参数详情
        Object[] params = new Object[parameterTypes.length];
        Map<String, String[]> parameterMap = req.getParameterMap();
        for (Map.Entry<String, String[]> param : parameterMap.entrySet()) {
            if (!paramIndex.containsKey(param.getKey())) { continue; }
            String string = Arrays.toString(param.getValue())
                    .replaceAll("\\[|\\]", "")
                    .replaceAll("\\s", "");
            params[paramIndex.get(param.getKey())] = string;
        }
        Object result = method.invoke(handler.getController(), params);
        if (result == null || result instanceof Void) { return null; }
        if (handler.getMethod().getReturnType() == BODModelAndView.class) {
            return (BODModelAndView) result;
        }

        return null;
    }
}
